package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.beans.LoginInfo;
import com.hxkcloud.patient.beans.RegisterNurseInfo;
import com.hxkcloud.patient.beans.resultbeans.ObjectResultBean;
import com.hxkcloud.patient.dborm.LoginInfoDao;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.BrightnessUtils;
import com.hxkcloud.patient.utils.SharedPreferenceUtil;
import com.hxkcloud.patient.utils.StringUtil;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONException;
import org.json.JSONObject;

import cn.jpush.android.api.JPushInterface;

/**
 * 个人信息(医护端)
 */
public class PersonalInfoForDNActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout titleLayout;
    private TextView titleTV;//标题
    private ImageView backIV;//回退按钮

    private EditText nameET;//姓名
    private EditText titleET;//职称
    private EditText departmentET;//科室
    private Button finishBtn;//完成按钮

    private boolean nameInput = false;
    private boolean titleInput = false;
    private boolean departmentInput = false;

    private String tel = "";
    private String password = "";
    private ObjectResultBean<RegisterNurseInfo> resultBean;

    //是否现在完善信息
    private PopupWindow popup_easynotice;
    private TextView tv_easynotice_title;
    private TextView tv_easynotice_cancel;
    private TextView tv_easynotice_func;

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_REGISTERNURSE_SUCCESS:
                if (msg.obj != null) {
                    resultBean = (ObjectResultBean<RegisterNurseInfo>) msg.obj;
                    loginInfo = new LoginInfo();
                    loginInfo.setDepartmentId("");
                    loginInfo.setAddress("");
                    loginInfo.setAge("");
                    loginInfo.setHeadImg("");
                    loginInfo.setHeight("");
                    loginInfo.setWeight("");
                    loginInfo.setSex("1");//给个默认的
                    loginInfo.setTitle(titleET.getText().toString());
                    loginInfo.setName(nameET.getText().toString().trim());
                    loginInfo.setUserId(resultBean.getData().getUserId());
                    loginInfo.setUserStyle(YjhApplication.userstyle_nurse);
                    loginInfo.setDepartmentName(departmentET.getText().toString().trim());
                    loginInfo.setNurseId(resultBean.getData().getNurseId());
                    LoginInfoDao loginInfoDao = new LoginInfoDao(mContext);
                    loginInfoDao.setUser(loginInfo);

                    new Thread() {
                        @Override
                        public void run() {
                            super.run();
                            try {
                                EMClient.getInstance().createAccount("ejh" + tel, "123456");
                                emClientLogin();
                            } catch (HyphenateException e) {
                                e.printStackTrace();
                                Log.e("EASE", e.toString());
                            }
                        }
                    }.start();

                    JPushInterface.setAlias(mContext, tel, null);

                    //zhugeio
                    try {
                        JSONObject personObject = new JSONObject();
                        personObject.put("name", nameET.getText().toString().trim());
                        personObject.put("phone", tel);
                        ZhugeSDK.getInstance().identify(getApplicationContext(), resultBean.getData().getUserId(),
                                personObject);
                    } catch (JSONException e) {
                    }

                    SharedPreferenceUtil.setIsrunning(mContext, true);
                    SharedPreferenceUtil.setLoginAccount(mContext, tel);
                    SharedPreferenceUtil.setLoginPassword(mContext, password);

                    toastMsg(resultBean.getMessage());
                    popup_easynotice.showAtLocation(titleLayout, Gravity.CENTER, 0, 0);
                    BrightnessUtils.lightOff(this);
                    return;
                }

                break;
            case MessageCode.NETWORKCODE_REGISTERNURSE_FAILURE:
                if (msg.obj != null) {
                    Toast.makeText(PersonalInfoForDNActivity.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                } else {
                    toastMsg(R.string.datacommitfail);
                }

                break;
        }
    }

    //环信登录
    private void emClientLogin() {
        EMClient.getInstance().login("ejh" + tel, "123456", new EMCallBack() {
            @Override
            public void onSuccess() {
                //以下两个方法是为了保证进入主页面后本地会话和群组都 load 完毕
                EMClient.getInstance().chatManager().loadAllConversations();
                EMClient.getInstance().groupManager().loadAllGroups();
                Log.e("EASE", "loginSuccess");
                dismisssLoading();
            }

            @Override
            public void onError(int i, String s) {
                Log.e("EASE", "登录聊天服务器失败！" + s);
            }

            @Override
            public void onProgress(int i, String s) {

            }
        });

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_layout_personalinfofordu);
        if (getIntent().hasExtra("tel")) {
            tel = getIntent().getStringExtra("tel");
        }
        if (getIntent().hasExtra("password")) {
            password = getIntent().getStringExtra("password");
        }
        initView();
        initPopup();
        initData();
        initListener();
    }

    @Override
    protected void initView() {
        titleLayout = (LinearLayout) findViewById(R.id.ll_title);
        setTitlePadding(titleLayout);
        titleTV = (TextView) findViewById(R.id.tv_title_title);
        titleTV.setText(getResources().getString(R.string.personalinfofordn_title));
        backIV = (ImageView) findViewById(R.id.iv_title_back);
        backIV.setVisibility(View.VISIBLE);
        nameET = (EditText) findViewById(R.id.personalinfofordn_et_name);
        nameET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (StringUtil.isEmpty(s.toString())) {
                    nameInput = false;
                    finishBtn.setBackgroundResource(R.drawable.bg_btn_light_corner);
                    finishBtn.setEnabled(false);
                } else {
                    nameInput = true;
                    if (titleInput && departmentInput) {
                        finishBtn.setBackgroundResource(R.drawable.bg_btn_lightgreen_corner);
                        finishBtn.setEnabled(true);
                    }
                }
            }


            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        titleET = (EditText) findViewById(R.id.personalinfofordn_et_title);
        titleET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (StringUtil.isEmpty(s.toString())) {
                    titleInput = false;
                    finishBtn.setBackgroundResource(R.drawable.bg_btn_light_corner);
                    finishBtn.setEnabled(false);
                } else {
                    titleInput = true;
                    if (nameInput && departmentInput) {
                        finishBtn.setBackgroundResource(R.drawable.bg_btn_lightgreen_corner);
                        finishBtn.setEnabled(true);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        departmentET = (EditText) findViewById(R.id.personalinfofordn_et_department);
        departmentET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (StringUtil.isEmpty(s.toString())) {
                    departmentInput = false;
                    finishBtn.setBackgroundResource(R.drawable.bg_btn_light_corner);
                    finishBtn.setEnabled(false);
                } else {
                    departmentInput = true;
                    if (titleInput && nameInput) {
                        finishBtn.setBackgroundResource(R.drawable.bg_btn_lightgreen_corner);
                        finishBtn.setEnabled(true);
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        finishBtn = (Button) findViewById(R.id.personalinfofordn_btn_finish);
        finishBtn.setEnabled(false);
    }

    private void initPopup() {
        popup_easynotice = new PopupWindow(this);
        View viewNotice = LayoutInflater.from(this).inflate(R.layout.popup_easynotice, null);
        popup_easynotice.setContentView(viewNotice);

        popup_easynotice.setWidth((int) (screenWidth * 0.7));
        popup_easynotice.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup_easynotice.setFocusable(true);
        popup_easynotice.setTouchable(true);
        popup_easynotice.setOutsideTouchable(true);
        popup_easynotice.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popup_easynotice.setAnimationStyle(R.style.popupwindow_anim_alpha);

        tv_easynotice_title = (TextView) viewNotice.findViewById(R.id.tv_easynotice_title);
        tv_easynotice_cancel = (TextView) viewNotice.findViewById(R.id.tv_easynotice_cancel);
        tv_easynotice_func = (TextView) viewNotice.findViewById(R.id.tv_easynotice_func);

        tv_easynotice_cancel.setOnClickListener(this);
        tv_easynotice_func.setOnClickListener(this);

        popup_easynotice.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                BrightnessUtils.lightOn(PersonalInfoForDNActivity.this);
            }
        });

        tv_easynotice_title.setText(getResources().getString(R.string.nursetocompleteinfo));
        tv_easynotice_cancel.setText(getResources().getString(R.string.nursetocompleteinfo_cancel));
        tv_easynotice_func.setText(getResources().getString(R.string.nursetocompleteinfo_sure));
    }

    @Override
    protected void initListener() {
        backIV.setOnClickListener(this);
        titleET.setOnClickListener(this);
        departmentET.setOnClickListener(this);
        finishBtn.setOnClickListener(this);

    }

    @Override
    protected void initData() {

    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.personalinfofordn_et_title:
                Intent titleIntent = new Intent(this, TitleForDNActivity.class);
                titleIntent.putExtra("name", titleET.getText().toString().trim());
                startActivityForResult(titleIntent, 1);
                break;
            case R.id.personalinfofordn_et_department:
                Intent departmentIntent = new Intent(this, DepartmentForDNActivity.class);
                departmentIntent.putExtra("name", departmentET.getText().toString().trim());
                startActivityForResult(departmentIntent, 2);
                break;
            case R.id.personalinfofordn_btn_finish:
                String name = nameET.getText().toString().trim();
                String title = titleET.getText().toString().trim();
                String department = departmentET.getText().toString().trim();
                loading();
                YiJiaHuNetWorkUtils.registerNurse(tel, password, name, title, department, handler);

                break;
            case R.id.tv_easynotice_cancel:
                popup_easynotice.dismiss();
                Intent finishIntent = new Intent(PersonalInfoForDNActivity.this, NurseFragmentActivity.class);
                startActivity(finishIntent);
                finish();
                removeAll();
                break;
            case R.id.tv_easynotice_func:
                popup_easynotice.dismiss();
                Intent finishIntent1 = new Intent(PersonalInfoForDNActivity.this, NurseFragmentActivity.class);
                finishIntent1.putExtra("index", 3);
                startActivity(finishIntent1);
                finish();
                removeAll();
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RESULT_OK:
                if (requestCode == 2) {
                    if (data != null) {
                        String departmentresult = data.getStringExtra("name");
                        departmentET.setText(departmentresult);
                    }
                }
                break;
            case 1:
                if (data != null) {
                    String titleresult = data.getStringExtra("title");
                    titleET.setText(titleresult);
                }

                break;
//            case 2:
//                if (data != null) {
//                    String departmentresult = data.getStringExtra("department");
//                    departmentET.setText(departmentresult);
//                }
//                break;


        }
    }
}
